<template>
  <div class="node-status">
    <div class="status-header">
      <h3>节点状态</h3>
      <el-button @click="refreshStatus" :loading="loading">
        <Icon icon="ant-design:reload-outlined" />
        刷新
      </el-button>
    </div>
    
    <div class="status-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <el-table v-else :data="displayNodeStatusList" style="width: 100%" :row-class-name="getRowClassName">
        <el-table-column prop="nodeName" label="节点名称" min-width="180">
          <template #default="scope">
            <div class="node-name-cell">
              <Icon :icon="getNodeIcon(scope.row.taskType)" class="node-icon" />
              <span>{{ scope.row.nodeName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="taskType" label="节点类型" min-width="150">
          <template #default="scope">
            <el-tag size="small" :type="getNodeTypeTagType(scope.row.taskType)">
              {{ getNodeTypeText(scope.row.taskType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="120">
          <template #default="scope">
            <div class="status-cell">
              <Icon :icon="getStatusIcon(scope.row.status)" class="status-icon" />
              <el-tag :type="getNodeStatusType(scope.row.status)" size="small" effect="light">
                {{ getNodeStatusText(scope.row.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="执行人" min-width="140">
          <template #default="scope">
            <div class="assignee-cell">
              <Icon icon="ant-design:user-outlined" class="assignee-icon" />
              <span>{{ scope.row.assignee || scope.row.userName || scope.row.approver || '系统' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="开始时间" min-width="180">
          <template #default="scope">
            <div class="time-cell">
              <Icon icon="ant-design:clock-circle-outlined" class="time-icon" />
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="completeTime" label="结束时间" min-width="180">
          <template #default="scope">
            <div class="time-cell">
              <Icon icon="ant-design:check-circle-outlined" class="time-icon" />
              <span>{{ formatDateTime(scope.row.completeTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="耗时" min-width="120">
          <template #default="scope">
            <div class="duration-cell">
              <Icon icon="ant-design:field-time-outlined" class="duration-icon" />
              <el-tag size="small" type="info" effect="plain">
                {{ extractDuration(scope.row.description) || calculateDuration(scope.row.createTime, scope.row.completeTime) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="viewNodeDetail(scope.row)"
            >
              <Icon icon="ant-design:eye-outlined" />
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="!loading && displayNodeStatusList.length === 0" class="empty-status">
        <Icon icon="ant-design:inbox-outlined" />
        <p>暂无节点状态信息</p>
        <el-button @click="refreshStatus" type="primary" size="small">
          重新加载
        </el-button>
      </div>
    </div>
    
    <!-- 节点详情弹窗 -->
    
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Icon from '@/components/Icon/Icon.vue'

// 引入统一的夜间模式样式
import '../styles/dark-theme.css'

const props = defineProps({
  processData: {
    type: Object,
    default: null
  },
  nodeStatusList: {
    type: Array,
    default: () => []
  },
  processInstanceId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['node-detail'])

// 状态管理
const loading = ref(false)

// 计算属性：显示的节点状态列表
const displayNodeStatusList = computed(() => {
  return props.nodeStatusList || []
})

// 刷新状态
const refreshStatus = () => {
  emit('node-detail', { action: 'refresh' })
}

// 查看节点详情
const viewNodeDetail = (nodeData) => {
  emit('node-detail', nodeData)
}

// 获取节点类型文本
const getNodeTypeText = (type) => {
  const typeMap = {
    'startEvent': '开始事件',
    'userTask': '用户任务',
    'serviceTask': '服务任务',
    'scriptTask': '脚本任务',
    'exclusiveGateway': '排他网关',
    'parallelGateway': '并行网关',
    'inclusiveGateway': '包容网关',
    'endEvent': '结束事件',
    'intermediateCatchEvent': '中间捕获事件',
    'intermediateThrowEvent': '中间抛出事件',
    'boundaryEvent': '边界事件'
  }
  return typeMap[type] || type
}

// 获取节点类型图标
const getNodeIcon = (type) => {
  const iconMap = {
    'startEvent': 'ant-design:play-circle-outlined',
    'userTask': 'ant-design:user-outlined',
    'serviceTask': 'ant-design:api-outlined',
    'scriptTask': 'ant-design:code-outlined',
    'exclusiveGateway': 'ant-design:swap-outlined',
    'parallelGateway': 'ant-design:swap-outlined',
    'inclusiveGateway': 'ant-design:swap-outlined',
    'endEvent': 'ant-design:check-circle-outlined',
    'intermediateCatchEvent': 'ant-design:cloud-outlined',
    'intermediateThrowEvent': 'ant-design:cloud-upload-outlined',
    'boundaryEvent': 'ant-design:safety-certificate-outlined'
  }
  return iconMap[type] || 'ant-design:info-circle-outlined'
}

// 获取节点类型标签类型
const getNodeTypeTagType = (type) => {
  const typeMap = {
    'startEvent': 'info',
    'userTask': 'primary',
    'serviceTask': 'success',
    'scriptTask': 'warning',
    'exclusiveGateway': 'info',
    'parallelGateway': 'info',
    'inclusiveGateway': 'info',
    'endEvent': 'success',
    'intermediateCatchEvent': 'info',
    'intermediateThrowEvent': 'info',
    'boundaryEvent': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取节点状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    'COMPLETED': 'ant-design:check-circle-outlined',
    'ACTIVE': 'ant-design:play-circle-outlined',
    'PENDING': 'ant-design:hourglass-outlined',
    'WAITING': 'ant-design:clock-circle-outlined',
    'CANCELLED': 'ant-design:close-circle-outlined',
    'SUSPENDED': 'ant-design:pause-circle-outlined',
    'RUNNING': 'ant-design:loading-outlined',
    'FINISHED': 'ant-design:check-circle-outlined',
    'TERMINATED': 'ant-design:close-circle-outlined'
  }
  return iconMap[status] || 'ant-design:info-circle-outlined'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  
  try {
    let date
    
    // 处理数组格式的时间 [year, month, day, hour, minute, second]
    if (Array.isArray(dateTime)) {
      if (dateTime.length >= 6) {
        const [year, month, day, hour, minute, second] = dateTime
        date = new Date(year, month - 1, day, hour, minute, second) // month需要减1，因为Date构造函数中月份是0-11
      } else {
        return '-'
      }
    } else if (typeof dateTime === 'string') {
      // 处理ISO格式的日期字符串
      if (dateTime.includes('T') || dateTime.includes('Z')) {
        date = new Date(dateTime)
      } else {
        // 处理其他格式的日期字符串
        date = new Date(dateTime.replace(/-/g, '/'))
      }
    } else if (dateTime instanceof Date) {
      date = dateTime
    } else {
      // 尝试直接创建Date对象
      date = new Date(dateTime)
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '-'
    }
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '-'
  }
}

// 提取耗时信息
const extractDuration = (description) => {
  if (!description) return null
  
  // 匹配多种耗时格式
  const patterns = [
    /处理时长:\s*(\d+[秒分时天])/,
    /(\d+[秒分时天])/,
    /(\d+)\s*秒/,
    /(\d+)\s*分钟/,
    /(\d+)\s*小时/,
    /(\d+)\s*天/
  ]
  
  for (const pattern of patterns) {
    const match = description.match(pattern)
    if (match) {
      return match[1] || match[0]
    }
  }
  
  return null
}

// 计算耗时
const calculateDuration = (startTime, endTime) => {
  if (!startTime || !endTime) return '-'
  
  try {
    let start, end
    
    // 处理开始时间
    if (Array.isArray(startTime)) {
      const [year, month, day, hour, minute, second] = startTime
      start = new Date(year, month - 1, day, hour, minute, second)
    } else {
      start = new Date(startTime)
    }
    
    // 处理结束时间
    if (Array.isArray(endTime)) {
      const [year, month, day, hour, minute, second] = endTime
      end = new Date(year, month - 1, day, hour, minute, second)
    } else {
      end = new Date(endTime)
    }
    
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      return '-'
    }
    
    const diff = end.getTime() - start.getTime()
    
    if (diff < 0) return '-'
    
    const seconds = Math.floor(diff / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)
    
    if (days > 0) return `${days}天`
    if (hours > 0) return `${hours}小时`
    if (minutes > 0) return `${minutes}分钟`
    return `${seconds}秒`
  } catch (error) {
    return '-'
  }
}

// 获取节点状态类型（增强版）
const getNodeStatusType = (status) => {
  const statusMap = {
    'COMPLETED': 'success',
    'ACTIVE': 'primary',
    'PENDING': 'warning',
    'WAITING': 'info',
    'CANCELLED': 'danger',
    'SUSPENDED': 'warning',
    'RUNNING': 'primary',
    'FINISHED': 'success',
    'TERMINATED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取节点状态文本（增强版）
const getNodeStatusText = (status) => {
  const statusMap = {
    'COMPLETED': '已完成',
    'ACTIVE': '进行中',
    'PENDING': '待处理',
    'WAITING': '等待中',
    'CANCELLED': '已取消',
    'SUSPENDED': '已暂停',
    'RUNNING': '运行中',
    'FINISHED': '已完成',
    'TERMINATED': '已终止'
  }
  return statusMap[status] || status
}

// 获取行类名
const getRowClassName = ({ row }) => {
  if (row.status === 'COMPLETED') {
    return 'completed-row'
  } else if (row.status === 'CANCELLED') {
    return 'cancelled-row'
  } else if (row.status === 'SUSPENDED') {
    return 'suspended-row'
  } else if (row.status === 'TERMINATED') {
    return 'terminated-row'
  }
  return ''
}

// 暴露方法给父组件
defineExpose({
  refreshStatus
})
</script>

<style scoped>
.node-status {
  padding: 20px 0;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-header h3 {
  margin: 0;
  color: #1a1a1a;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

:deep(.el-table__body-wrapper) {
  min-height: 400px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
  padding: 16px 12px;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table__body td) {
  padding: 20px 12px;
  border-bottom: 1px solid #f0f0f0;
  height: 60px;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

/* 内容区域样式 */
.status-content {
  min-height: 600px;
  padding: 0 4px;
}

.loading-container {
  padding: 20px;
}

.empty-status {
  text-align: center;
  color: #999;
  padding: 60px 0;
}

.empty-status :deep(svg) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ccc;
}

.empty-status p {
  margin-bottom: 16px;
  font-size: 14px;
}

.node-detail {
  padding: 10px 0;
}

/* 夜间模式支持 */
:deep(.dark) .status-header h3 {
  color: #ffffff;
}

:deep(.dark) .empty-status {
  color: #666;
}

:deep(.dark) .empty-status :deep(svg) {
  color: #555;
}

/* 新增的行样式 */
:deep(.completed-row) {
  background-color: #f0f9eb; /* 浅绿色背景 */
}

:deep(.cancelled-row) {
  background-color: #fef0f0; /* 浅红色背景 */
}

:deep(.suspended-row) {
  background-color: #fffbe6; /* 浅黄色背景 */
}

:deep(.terminated-row) {
  background-color: #fde2e2; /* 浅橙色背景 */
}

/* 单元格样式 */
.node-name-cell,
.status-cell,
.assignee-cell,
.time-cell,
.duration-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.node-icon,
.status-icon,
.assignee-icon,
.time-icon,
.duration-icon {
  font-size: 14px;
  color: #909399;
}

.node-icon {
  color: #409eff;
}

.status-icon {
  font-size: 12px;
}

/* 夜间模式支持 */
:deep(.dark) .completed-row {
  background-color: rgba(103, 194, 58, 0.1);
}

:deep(.dark) .cancelled-row {
  background-color: rgba(245, 108, 108, 0.1);
}

:deep(.dark) .suspended-row {
  background-color: rgba(230, 162, 60, 0.1);
}

:deep(.dark) .terminated-row {
  background-color: rgba(144, 147, 153, 0.1);
}

:deep(.dark) .node-icon,
:deep(.dark) .status-icon,
:deep(.dark) .assignee-icon,
:deep(.dark) .time-icon,
:deep(.dark) .duration-icon {
  color: #a0a0a0;
}

:deep(.dark) .node-icon {
  color: #409eff;
}
</style> 